package com.example.houpicture.service.impl;

import com.example.houpicture.entity.TbRoomInfo;
import com.example.houpicture.mapper.TbRoomInfoMapper;
import com.example.houpicture.service.ITbRoomInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.org.ddto.*;
import com.org.enums.ConditionType;
import com.org.vo.TbRoomInfoResponseVo;
import com.org.vo.TbRoomInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 龚梦
 * @since 2021-04-07
 */
@Service
public class TbRoomInfoServiceImpl extends ServiceImpl<TbRoomInfoMapper, TbRoomInfo> implements ITbRoomInfoService {

    @Override
    public  Map<String, Object>  roomStatusList(PageRoomStatusDto pageRoomStatusDto) {
        Map<String, Object> resultMap = new HashMap<>();
        //分页
        PageHelper.startPage(pageRoomStatusDto.getPageNo(), pageRoomStatusDto.getPageSize());
        // 房产类型 集1分散式 2中式 hostType
        if (pageRoomStatusDto.getHostType() == 1) {
            List<TbRoomInfoResponseVo> list = baseMapper.roomStatusListFs(pageRoomStatusDto);
            PageInfo<TbRoomInfoResponseVo> info = new PageInfo<>(list);
            List<TbRoomInfoResponseVo> roomlist = info.getList();
            if (roomlist.size() > 0) {
                roomlist = this.pushRecordMini(info.getList());
                info.setList(roomlist);
            }
            resultMap.put("responseFsVos",info);
            return resultMap;
        }else {
            // pageRoomStatusDto.setPageSize(1);
            // 集中式
            List<TbRoomInfoResponseVo> roomListByConcentrate = baseMapper.roomStatusListJz(pageRoomStatusDto);
            PageInfo<TbRoomInfoResponseVo> InfoJz = new PageInfo<>(roomListByConcentrate);
            List<TbRoomInfoResponseVo> list = InfoJz.getList();
            if (InfoJz.getList().size()>0){
                pageRoomStatusDto.setHouseId(list.get(0).getHouseId());
                list = baseMapper.roomStatusListDetailJz(pageRoomStatusDto);
            }
            List<PageTbRoomInfoJzGyResponseDTO> res = null;
            if (list.size()>0){
                res = this.pushJzRecord(list,pageRoomStatusDto.getPreName());
            }
            resultMap.put("responseJzVos",InfoJz);
            resultMap.put("TbRoomInfoJzGy",res);
            return resultMap;
        }
    }

    /**
     *  分散式 - 房源赋值
     * @param minis
     * @return
     */
    private List<TbRoomInfoResponseVo> pushRecordMini(List<TbRoomInfoResponseVo> minis) {
        Set<String> roomKeySet = new HashSet<>();
        Set<String> miniKey = new HashSet<>();
        Map<String, List<PageRoomInfoMiniResponseDTO>> miniMap = new HashMap<>();
        List<TbRoomInfoResponseVo> res = new ArrayList<>();
        List<TbRoomInfoResponseVo> ho = new ArrayList<>();
        List<PageRoomInfoMiniResponseDTO> miniTemp;
        for (TbRoomInfoVo tbRoomInfoVo : minis) {
            String key = tbRoomInfoVo.getPreId() + "-" +tbRoomInfoVo.getHouseId();
            if (!roomKeySet.contains(key)){
                TbRoomInfoResponseVo tbRoomInfoResponseVo = new TbRoomInfoResponseVo();
                StringBuffer buffer = new StringBuffer();
                if (org.apache.commons.lang3.StringUtils.isNotBlank(tbRoomInfoVo.getBuildingNo())){
                    buffer.append(tbRoomInfoVo.getBuildingNo()+"栋");
                }
                if (org.apache.commons.lang3.StringUtils.isNotBlank(tbRoomInfoVo.getUnitNo())) {
                    buffer.append(tbRoomInfoVo.getUnitNo()+ "单元");
                }
                if (org.apache.commons.lang3.StringUtils.isNotBlank(tbRoomInfoVo.getRoomNo())) {
                    buffer.append(tbRoomInfoVo.getRoomNo());
                }
                if (StringUtils.isNotBlank(buffer)) {
                    tbRoomInfoVo.setBdiNo(buffer.toString());
                }
                tbRoomInfoResponseVo.setRoomCount(tbRoomInfoVo.getRoomCount());
                BeanUtils.copyProperties(tbRoomInfoVo,tbRoomInfoResponseVo);
                ho.add(tbRoomInfoResponseVo);
                roomKeySet.add(key);
            }
            // 初始计算房源
            PageRoomInfoMiniResponseDTO mini = this.getComputeRoomMini(tbRoomInfoVo);
            if (null != mini.getRoomId()) {
                mini.setRoomCode(mini.getRoomCode());
                String putKey = mini.getHouseId();
                List<PageRoomInfoMiniResponseDTO> list = miniMap.get(putKey);
                if (null != list) {
                    // this.checkMini(mini, list);
                    miniMap.get(putKey).add(mini);
                } else {
                    miniTemp = new ArrayList<>();
                    miniTemp.add(mini);
                    miniMap.put(putKey, miniTemp);
                }
                miniKey.add(tbRoomInfoVo.getRoomId());
            }
        }
        // 房产
        for (TbRoomInfoResponseVo s : ho) {
            String getKey = s.getHouseId();
            List<PageRoomInfoMiniResponseDTO> list = miniMap.get(getKey);
            if (null != list && list.size() > 0) {
                s.setRoomCount(list.size());
                s.setRoomMni(list);
                s.setFindPreName(s.getPreName());
                res.add(s);
            }
        }
        return res;
    }

    /**
     *
     * @Description: 计算 - 房源状态
     * @param pdto
     * @return PageTbRoomInfoMiniResponseDTO
     */
    private PageRoomInfoMiniResponseDTO getComputeRoomMini(TbRoomInfoVo pdto) {
        PageRoomInfoMiniResponseDTO res = new PageRoomInfoMiniResponseDTO();
        List<Map<String, Object>> dList;
        Map<String, Object> dmap;
        int roomStatus = pdto.getRoomStatus();
        if (1 == roomStatus) { // 已租出
            dList = new ArrayList<>();
            int cEndDate = 0;
            int rcDate = 0;
            if (null != pdto.getCEndDate()) {
                cEndDate = Integer.parseInt(pdto.getCEndDate());// 合同天数
            }
            if (null != pdto.getRcDates()) {
                rcDate = Integer.parseInt(pdto.getRcDates());// 付款天数
            }
            // 计算租金日期
            if (0 < rcDate && rcDate <= 10) {
                dmap = new HashMap<>();
                dmap.put("FangtaiType", ConditionType.SHOUFEI.getIndex()); // 收费
                dmap.put("total", Math.abs(rcDate));
                dList.add(dmap);
            } else if (rcDate < 0) {
                dmap = new HashMap<>();
                dmap.put("FangtaiType", ConditionType.QIANFEI.getIndex()); // 欠费
                dmap.put("total", Math.abs(rcDate));
                dList.add(dmap);
            }
            // 计算合同
            if (0 < cEndDate && cEndDate <= 30) {
                dmap = new HashMap<>();
                dmap.put("FangtaiType", ConditionType.KUAIDAO.getIndex()); // 快到
                dmap.put("total", Math.abs(cEndDate));
                dList.add(dmap);
                if (pdto.getCheckTerm() == 0) { // 可续约
                    pdto.setCheckTerm(6);
                } else if (cEndDate < 0) {
                    dmap = new HashMap<>();
                    dmap.put("FangtaiType", ConditionType.DAOQI.getIndex()); // 到期
                    dmap.put("total", Math.abs(cEndDate));
                    dList.add(dmap);
                }
            }
            if (null == pdto.getCEndDate() && null == pdto.getRcDates()) {
                dmap = new HashMap<>();
                dmap.put("FangtaiType", ConditionType.YIDENGJI.getIndex()); // 已登记
                dList.add(dmap);
                pdto.setCheckRegister(1);
            }
            pdto.setMiniDetail(dList);

        } else if (2 == roomStatus) {// 装修中
            dList = new ArrayList<>();
            dmap = new HashMap<>();
            double finishDate = 0L;
            if (null != pdto.getFinishDate()) {
                finishDate = Integer.parseInt(pdto.getFinishDate());
            }
            if (finishDate != 0) {
                dmap.put("FangtaiType", ConditionType.ZHUANGXIU.getIndex());// 房态类型 装修
                dmap.put("total", Math.abs(finishDate));// 天数
                dList.add(dmap);
            }
            pdto.setMiniDetail(dList);
        } else if (0 == roomStatus) { // 0 默认 待租中（空置）
            dList = new ArrayList<>();
            dmap = new HashMap<>();
            Integer vacancyDate = 0;
            if (null != pdto.getVacancyDate()) {
                vacancyDate = Integer.parseInt(pdto.getVacancyDate());
            }
            if (vacancyDate != 0) {
                dmap.put("FangtaiType", ConditionType.KONGZHI.getIndex());// 房态类型 空置
                dmap.put("total", Math.abs(vacancyDate));// 天数
                dList.add(dmap);
                pdto.setLeisureDate(Math.abs(vacancyDate));
            }
            pdto.setLeisureFlag(1);
            pdto.setMiniDetail(dList);
        }
        BeanUtils.copyProperties(pdto, res);
        res.setTenantName(res.getTenantName());
        return res;
    }

    /**
     *  计算 - 集中式房源赋值
     * @param minis
     * @param searchName
     * @return
     */
    private List<PageTbRoomInfoJzGyResponseDTO> pushJzRecord(List<TbRoomInfoResponseVo> minis, String searchName) {
        Map<String, Integer> countMap = new HashMap<>();
        Map<String, Integer> numMap = new HashMap<>();
        List<PageTbRoomInfoJzGyResponseDTO> gy = new ArrayList<>(); // 公寓s
        List<PageTbRoomInfoJzLdResponseDTO> ld = new ArrayList<>(); // 楼栋s
        List<PageTbRoomInfoJzLcResponseDTO> lc = new ArrayList<>(); // 楼层s
        List<PageRoomInfoMiniResponseDTO> fy; // 房源s
        PageTbRoomInfoJzGyResponseDTO g;
        PageTbRoomInfoJzLdResponseDTO d;// 楼栋
        PageTbRoomInfoJzLcResponseDTO c;// 楼层
        Set<String> gySet = new HashSet<>();
        Set<String> ldSet = new HashSet<>();
        Set<String> lcSet = new HashSet<>();
        Set<String> mkey = new HashSet<>();
        Map<String, List<PageTbRoomInfoJzLdResponseDTO>> ldMap = new HashMap<>();
        Map<String, List<PageTbRoomInfoJzLcResponseDTO>> lcMap = new HashMap<>();
        Map<String, List<PageRoomInfoMiniResponseDTO>> fyMap = new HashMap<>();
        for (TbRoomInfoResponseVo m : minis) {
            String gyConKey = m.getHouseId();
            // 初始公寓
            if (!gySet.contains(gyConKey)) {
                g = new PageTbRoomInfoJzGyResponseDTO();
                BeanUtils.copyProperties(m, g);
                g.setFindFlatName(g.getFlatName());
                g.setPreName(g.getPreName());
                gy.add(g);
                gySet.add(gyConKey);
            }
            // 初始楼栋
            String ldConsKey = m.getHouseId() + "-" + m.getBuildingName();
            if (!ldSet.contains(ldConsKey)) {
                d = new PageTbRoomInfoJzLdResponseDTO();
                d.setBuildingName(m.getBuildingName());
                d.setHouseId(m.getHouseId());
                ld.add(d);
                ldSet.add(ldConsKey);
            }
            // 初始楼层
            String lcConsKey = m.getHouseId() + "-" + m.getBuildingName() + "-" + m.getFloor();
            if (!lcSet.contains(lcConsKey)) {
                c = new PageTbRoomInfoJzLcResponseDTO();
                c.setBuildingName(m.getBuildingName());
                c.setFloor(m.getFloor()+"");
                c.setHouseId(m.getHouseId());
                lc.add(c);
                lcSet.add(lcConsKey);
            }
            // 初始计算房源
            if (!mkey.contains(m.getRoomId()) || null != m.getRcDates()) {
                PageRoomInfoMiniResponseDTO mini = this.getComputeRoomMini(m);
                mini.setRoomCode(mini.getRoomCode());
                if (null != mini.getRoomId()) {
                    String putKey = mini.getHouseId() + "-" + mini.getBuildingName() + "-" + mini.getFloor();
                    List<PageRoomInfoMiniResponseDTO> list = fyMap.get(putKey);
                    if (null != list) {
                        // this.checkMini(mini, list);
                        fyMap.get(putKey).add(mini);

                    } else {
                        fy = new ArrayList<>();
                        fy.add(mini);
                        fyMap.put(putKey, fy);
                    }
                    // 记录时间
                    String countKey = mini.getHouseId() + "-" + mini.getBuildingName();
                    Integer count = countMap.get(countKey);
                    if (null == count) {
                        if (!mkey.contains(m.getRoomId())) {
                            countMap.put(countKey, 1);
                        }
                    } else {
                        if (!mkey.contains(m.getRoomId())) {
                            count++;
                            countMap.put(countKey, count);
                        }
                    }
                    if (mini.getLeisureFlag() == 1) {
                        Integer num = numMap.get(countKey);
                        if (null == num) {
                            numMap.put(countKey, 1);
                        } else {
                            num++;
                            numMap.put(countKey, num);
                        }
                    }
                }
                mkey.add(m.getRoomId());
            }
        }
        List<PageTbRoomInfoJzLcResponseDTO> lcTemp;
        // 计算楼层
        for (PageTbRoomInfoJzLcResponseDTO l : lc) {
            String getkKey = l.getHouseId() + "-" + l.getBuildingName() + "-" + l.getFloor();
            List<PageRoomInfoMiniResponseDTO> list = fyMap.get(getkKey);
            if (null != list && list.size() > 0) {
                l.setMiniDetail(list);
                String key = l.getHouseId() + "-" + l.getBuildingName();
                if (null != lcMap.get(key)) {
                    lcMap.get(key).add(l);
                } else {
                    lcTemp = new ArrayList<>();
                    lcTemp.add(l);
                    lcMap.put(key, lcTemp);
                }
            }
        }
        List<PageTbRoomInfoJzLdResponseDTO> ldTemp;
        // 计算楼栋
        for (PageTbRoomInfoJzLdResponseDTO ds : ld) {
            String getKey = ds.getHouseId() + "-" + ds.getBuildingName();
            List<PageTbRoomInfoJzLcResponseDTO> list = lcMap.get(getKey);
            if (null != list && list.size() > 0) {
                ds.setMiniDetail(list);
                if (null != countMap.get(getKey)) {
                    ds.setTotal(countMap.get(getKey));
                }
                if (null != numMap.get(getKey)) {
                    ds.setVacancyNum(numMap.get(getKey));
                }

                if (null != ldMap.get(ds.getHouseId())) {
                    ldMap.get(ds.getHouseId()).add(ds);
                } else {
                    ldTemp = new ArrayList<>();
                    ldTemp.add(ds);
                    ldMap.put(ds.getHouseId(), ldTemp);
                }
            }
        }
        // 计算公寓
        for (PageTbRoomInfoJzGyResponseDTO gs : gy) {
            List<PageTbRoomInfoJzLdResponseDTO> list = ldMap.get(gs.getHouseId());
            if (null != list && list.size() > 0) {
                gs.setLdDetail(list);
            }
        }

        return gy;

    }
}
